package com.itheima.commons.utils;

import cn.hutool.core.codec.Base64;
import com.baidu.aip.face.AipFace;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Properties;

/**
 * @author yaohu
 */
public class FaceDetectUtil {
    //设置APPID/AK/SK
    public static String APP_ID;
    public static String API_KEY;
    public static String SECRET_KEY;

    static {
        // 读取配置文件
        Properties properties = new Properties();
        try {
            properties.load(FaceDetectUtil.class.getClassLoader().getResourceAsStream("baiduapi.properties"));
            APP_ID = properties.getProperty("BAIDU_APP_ID");
            API_KEY = properties.getProperty("BAIDU_API_KEY");
            SECRET_KEY = properties.getProperty("BAIDU_SECRET_KEY");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Boolean detectFace(byte[] imageBytes) {
        // 初始化一个AipFace
        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
        
        // 可选：设置网络连接参数
        client.setConnectionTimeoutInMillis(2000);
        client.setSocketTimeoutInMillis(60000);

        // 人脸检测
        JSONObject res = client.detect(Base64.encode(imageBytes), "BASE64", null);
        return "SUCCESS".equalsIgnoreCase(res.getString("error_msg"));
    }
}